/* eslint-disable no-async-promise-executor */
import { login, logout } from '@/api'
import storage from '@/utils/storage'
export default {
  namespaced: true,
  state: {
    userInfo: storage.getItem('userInfo'),
    token: storage.getItem('token')
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
    },

    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    REMOVE_TOKEN(state) {
      storage.clearAll()
      // storage.clearItem('token')
      // storage.clearItem('userInfo')
      // const token = storage.getItem('token')
      // const userInfo = storage.getItem('userInfo')
      // state.token = token
      // state.userInfo = userInfo
    }
  },
  actions: {
    login({ commit }, payload) {
      return new Promise(async (resolve, reject) => {
        try {
          const { data: { message } } = await login({ username: payload.username.trim(), password: payload.password.trim() })
          commit('SET_TOKEN', message.token)
          commit('SET_USER_INFO', message)
          storage.setItem('token', message.token)
          storage.setItem('userInfo', message)
          resolve()
        } catch (error) {
          reject(error)
        }
      })
    },
    logout({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          await logout()
          commit('REMOVE_TOKEN')
          resolve()
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}